import { useState } from "react";
import { Button, Space, Table } from "antd";
import { PlusOutlined, ReloadOutlined } from "@ant-design/icons";

export interface SmartTableProp {
  columns: any[];
  getTableData: any;
  showAddBtn: boolean;
}

export default function SmartTable(props: SmartTableProp) {
  const [pager, setPager] = useState({
    pageIndex: 1,
    pageSize: 10,
    total: 0
  });
  const [tbLoading, setTbLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const tableSize = "middle";

  function getTableData() {
    if (!props.getTableData) return;
    setTbLoading(true);
    props.getTableData()
      .then((res: any) => {
        if (res && res.success) {
          setTableData(res.data.list)
          setPager({
            ...pager,
            total: res.data.pageInfo.total
          });
        }
      })
      .finally(() => {
        setTbLoading(false)
      })
  }

  function renderToolbar() {
    return (
      <div>
        <Space size={"large"}>
          {
            props.showAddBtn ? (
              <Button
                type="primary"
                icon={<PlusOutlined />}>
                新建
              </Button>
            ) : null
          }
          <Space size={"middle"}>
            <a className="ui-hover-text" onClick={e => e.preventDefault()}>
              <ReloadOutlined onClick={getTableData}/>
            </a>
          </Space>
        </Space>
      </div>
    )
  }

  return (
    <div>
      { renderToolbar() }
      <Table
        rowKey={"id"}
        bordered
        columns={props.columns}
        size={tableSize}
        loading={tbLoading}
        dataSource={ tableData }
        pagination={{
          showQuickJumper: false,
          showTotal: () => `共 ${ pager.total } 条`,
          pageSize: pager.pageSize,
          total: pager.total,
          current: pager.pageIndex,
          onChange: (v) => setPager({ ...pager, pageIndex: v}),
        }}
      />
    </div>
  )
}
